$(function () {
   const total = $('.dataTables_info .total').attr('data-total') - 0
   let flag = false
   let totalData = null
   let index = 1
   const host = 'http://admi-yuliner.oss-cn-hangzhou.aliyuncs.com/'
   // 渲染分页器
   pagesToolHandler(total / 6)

   $($('#pages-tool > a')).on('click', function () {
      changePage($(this).text() - 0)
   })

   // 获取页面表单数据
   $.get('/storegoods/getpagesdata', res => {
      if (res.msg === 'ok') {
         localStorage.setItem('totalData', JSON.stringify(res.data))
      } else {
         totalData = []
      }
   })
   $('#selectId').on('change', function () {
      const num = $(this).val() - 0
      switch (num) {
         case 2:
            tableHandler(0, num)
            pagesToolHandler(total / 2)
            break
         case 4: tableHandler(0, num)
            pagesToolHandler(total / 4)
            break
         case 6: tableHandler(0, num)
            pagesToolHandler(total / 6)
            break
      }

      // 向本都存储中获取数据
      if (!flag) totalData = JSON.parse(localStorage.getItem('totalData'))
      flag = true // 禁止重复获取
      setPicAmimation()

      // 当点击切换页码时
      $($('#pages-tool > a')).on('click', function () {
         changePage($(this))
      })
   })


   // 点击上一页切换
   $('#DataTables_Table_1_previous').on('click', function () {
      if (index <= 1) return
      index--
      changeActive($(`#pages-tool > a:eq(${index - 1})`))

      // 重新渲染表格
      fn($('#selectId').val() - 0, index)
   })
   // 点击下一页
   $('#DataTables_Table_1_next').on('click', function () {
      if (index >= $('#pages-tool > a').length) return
      index++
      changeActive($(`#pages-tool > a:eq(${index - 1})`))
      fn($('#selectId').val() - 0, index)
   })

   /**
    * 封装渲染分页序号的函数
    * @param {*} end 
    */
   function pagesToolHandler(end) {
      let str = ''
      for (let i = 0; i < end; i++) {
         str += `<a tabindex="0" class="${i == 0 ? 'paginate_active' : 'paginate_button'}">${i + 1}</a>`
      }
      $('#pages-tool').html(str)
   }
   /**
    * 封装渲染表格数据函数
    * @param {*} star 
    * @param {*} end 
    */
   function tableHandler(star, end) {
      let str = ''
      let n = 0
      const data = JSON.parse(localStorage.getItem('totalData'))
      for (let i = star; i < end; i++, n++) {
         str += `
            <tr align="center">
               <td>${n + 1}</td>
               <td>${data[i].foodname}</td>
               <td class="user-pic">
                  <!-- 如用户上传 logo 则使用用户 logo, 不上传则使用默认 -->
                  <img src="${data[i].foodpic === 'default.webp' ? '/images/default.webp' : host + data[i].foodpic}" alt="" style="width: 30px; cursor: pointer;">
               </td>
               <td>${data[i].descr}</td>
               <td>${data[i].price}</td>
               <td>${data[i].shopname}</td>
               <td>
                  <span class="btn-group">
                     <button href="#" class="btn btn-small btn-danger btn-del"
                        data-url="/storegoods/goodsdel?id=${data[i].id}&foodpic=${data[i].foodpic}"
                        title="删除">
                        <i class="icon-trash"></i>
                     </button>
                     <a href="/storegoods/goodsupdate?id=${data[i].id}&shopname=${data[i].shopname}" class="btn btn-small btn-primary" style="margin-left: 4px;" title="修改">
                        <i class="icon-pencil-2"></i>
                     </a>
                  </span>
               </td>
            </tr>
         `
      }
      $('.container .mws-table tbody').html(str)
   }

   /**
    * // 切换页码函数
    * @param {*} target 
    */
   function changePage(target) {
      let num = target.text() - 0
      index = num
      let size = $('#selectId').val() - 0
      changeActive(target)
      let data = totalData.filter((item, index) => {
         return index + 1 <= size * num && index + 1 > size * num - size
      })
      let str = ''
      for (let i = 0; i < data.length; i++) {
         str += `
            <tr align="center">
               <td>${i + 1}</td>
               <td>${data[i].foodname}</td>
               <td class="user-pic">
                  <!-- 如用户上传 logo 则使用用户 logo, 不上传则使用默认 -->
                  <img src="${data[i].foodpic === 'default.webp' ? '/images/default.webp' : host + data[i].foodpic}" alt="" style="width: 30px; cursor: pointer;">
               </td>
               <td>${data[i].descr}</td>
               <td>${data[i].price}</td>
               <td>${data[i].shopname}</td>
               <td>
                  <span class="btn-group">
                     <button href="#" class="btn btn-small btn-danger btn-del"
                        data-url="/storegoods/goodsdel?id=${data[i].id}&foodpic=${data[i].foodpic}"
                        title="删除">
                        <i class="icon-trash"></i>
                     </button>
                     <a href="/storegoods/goodsupdate?id=${data[i].id}&shopname=${data[i].shopname}" class="btn btn-small btn-primary" style="margin-left: 4px;" title="修改">
                        <i class="icon-pencil-2"></i>
                     </a>
                  </span>
               </td>
            </tr>
         `
      }
      $('.container .mws-table tbody').html(str)
   }

   /**
    * 点击页码切换选中状态
    * @param {DOM} target 被选中的目标对象
    */
   function changeActive(target) {
      $('#pages-tool').find('.paginate_active').removeClass('paginate_active').addClass('paginate_button')
      target.addClass('paginate_active')
   }

   function fn(size, num) {
      let data = totalData.filter((item, index) => {
         return index + 1 <= size * num && index + 1 > size * num - size
      })
      let str = ''
      for (let i = 0; i < data.length; i++) {
         str += `
            <tr align="center">
               <td>${i + 1}</td>
               <td>${data[i].foodname}</td>
               <td class="user-pic">
                  <!-- 如用户上传 logo 则使用用户 logo, 不上传则使用默认 -->
                  <img src="${data[i].foodpic === 'default.webp' ? '/images/default.webp' : host + data[i].foodpic}" alt="" style="width: 30px; cursor: pointer;">
               </td>
               <td>${data[i].descr}</td>
               <td>${data[i].price}</td>
               <td>${data[i].shopname}</td>
               <td>
                  <span class="btn-group">
                     <button href="#" class="btn btn-small btn-danger btn-del"
                        data-url="/storegoods/goodsdel?id=${data[i].id}&foodpic=${data[i].foodpic}"
                        title="删除">
                        <i class="icon-trash"></i>
                     </button>
                     <a href="/storegoods/goodsupdate?id=${data[i].id}&shopname=${data[i].shopname}" class="btn btn-small btn-primary" style="margin-left: 4px;" title="修改">
                        <i class="icon-pencil-2"></i>
                     </a>
                  </span>
               </td>
            </tr>
         `
      }
      $('.container .mws-table tbody').html(str)
   }

   function setPicAmimation() {
      // 初始化
      $('#user-info-pic').css('transition', ' all .45s linear')

      // 开启头像预览
      $('.container .user-pic').on('click', function () {
         let src = $(this).find('img').attr('src')
         $('#user-info-pic img').prop('src', src)
         $('#user-info-pic').css({
            opacity: 0,
            display: 'block'
         })
         setTimeout(() => {
            $('#user-info-pic').css({
               opacity: 1,
            })
         }, 100)
      })

      // 关闭图片预览
      $('#user-info-pic .btn-close').on('click', function () {
         $('#user-info-pic').css({
            opacity: 0
         })
         setTimeout(() => {
            $('#user-info-pic').css('display', 'none')
         }, 500)
      })
   }

})